import AuthApi from '@/api/auth';
import { COMMON_CONFIG } from '@/app.contants';
import Taro from '@tarojs/taro';
import { observable } from 'mobx';
import commonStore from './common';

const CACHE_USER = 'cacheUser';

const authStore = observable({
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  user: initUser(),

  //检查是否登录
  check(param: any = { block: false, redirect: false }) {
    // 检查
    if (this.user) {
      return true;
    } else {
      // 从未登录
      if (param.block) {
        //CommonFnc.goView('/pages/index/auth/index', {}, param.redirect)
      }
      return false;
    }
  },

  //微信登陆
  async wxLogin(param: any) {
    const res = await AuthApi.wxLogin(param);
    console.log(res);
    if (res.code === COMMON_CONFIG.SUCCESS) {
      this.saveUser(res.data, param.code);
    }
    return res.data;
  },

  //重新拉取用户信息
  async reload(id: string) {
    if (id) {
      const res = await AuthApi.userInfo(id);
      console.log(res);
      if (res.code === COMMON_CONFIG.SUCCESS) {
        this.saveUser(res.data);
      }
      return res.data;
    }
    return false;
  },

  //保存用户信息
  saveUser(user: any, code: string) {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    user.validTime = getTimestamp();
    this.user = user;
    commonStore.setToken(user.token);
    code && commonStore.setWxCode(code);
    Taro.setStorageSync(CACHE_USER, user);
  },
});

function initUser() {
  const user = Taro.getStorageSync(CACHE_USER);
  commonStore.setToken(user.token);
  return user;
}

function getTimestamp() {
  let timestamp = Date.parse(new Date().toString());
  timestamp = timestamp / 1000;
  console.log('当前时间戳为：' + timestamp);
  return timestamp;
}

export default authStore;
